package com.yj.springbootfastdfs.rest;

import com.yj.springbootfastdfs.common.FileResource;
import com.yj.springbootfastdfs.entity.Info;
import com.yj.springbootfastdfs.mapper.InfoMapper;
import com.yj.springbootfastdfs.service.FdfsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;

@RestController
@RequestMapping("fdfs")
public class UploadController {


    @Resource
    private FdfsService fdfsService;

    @Resource
    private InfoMapper infoMapper;

    @Resource
    private FileResource fileResource;

    @PostMapping("upload")
    public Info upload(MultipartFile file) throws Exception{

        if (file == null) {
            throw new RuntimeException("文件不能为空！");
        }
        String path = null;
        Info info = null;
        String originalFilename = file.getOriginalFilename();

        if (StringUtils.isNoneBlank(originalFilename)) {

            String[] split = originalFilename.split("\\.");
            System.out.println(Arrays.toString(split));
            String suffix = split[split.length - 1];
            if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg")
                    && suffix.equalsIgnoreCase("jpeg")) {
                throw new RuntimeException("图片格式不正确！");
            }

            path = fdfsService.upload(file, suffix,null);
            System.out.println(path);

            //将图片存到数据库中
            info = new Info();
            info.setName("yj");
            info.setPhoto(fileResource.getPath() + path);
            infoMapper.insert(info);
        }else {
            throw new RuntimeException("文件名不能为空！");
        }
        return info;
    }

}
